<?php
namespace App\Http\Controllers\Admin;
/*
                   _ooOoo_ 
                  o8888888o 
                  88" . "88 
                  (| -_- |) 
                  O\  =  /O 
               ____/`---'\____ 
             .'  \\|     |//  `. 
            /  \\|||  :  |||//  \ 
           /  _||||| -:- |||||-  \ 
           |   | \\\  -  /// |   | 
           | \_|  ''\---/''  |   | 
           \  .-\__  `-`  ___/-. / 
         ___`. .'  /--.--\  `. . __ 
      ."" '<  `.___\_<|>_/___.'  >'"". 
     | | :  `- \`.;`\ _ /`;.`/ - ` : | | 
     \  \ `-.   \_ __\ /__ _/   .-` /  / 
======`-.____`-.___\_____/___.-`____.-'====== 
                   `=---=' 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
         佛祖保佑       永无BUG 
*/  
//          佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
use App\Models\Category;
use Illuminate\Http\Request;
use App\Models\Teaches;
use Illuminate\Support\Facades\Response;
use App\Models\TeachesTags;
use App\Models\Tags;
use App\Models\Company;
use App\Models\TeachesChapter;
use App\Models\TeachesContent;
use App\User;

class TeachesController extends BaseController
{
    protected $catgory;
    protected $companys;
    
    /**
     * @see \App\Http\Controllers\Admin\BaseController::__construct()
     */
    public function __construct() {
        parent::__construct();
        $this->catgory = Category::where(array('app'=>'teaches','pid'=>0))->get();
        $this->companys = Company::where('is_teaches','=',1)->orderBy('teaches_at','desc')->orderBy('created_at','desc')->orderBy('id','desc')->get();
    }
    
    /**
     * Show the application dashboard to the user.
     *
     * @return Response
     */
    public function index(Request $req)
    {
        if(!$this->user->can('viewTeaches')) abort(405);
        $catid = $req->input('type');
        $title = $req->input('title');
        $username = $req->input('username');
        $status = $req->input('status',4);
        $query = Teaches::with('categorys');
        
        if(!empty($catid))
        {
            $query->whereIn('cat_id',$this->getSubCategory($catid));
        }
        if(!empty($title))
        {
            $query->where('name','like','%'.$title.'%');    
        }
        if(!empty($username))
        {
            $authorids = User::where('name','like','%'.$username.'%')->lists('id');
            $query->whereIn('user_id',$authorids);
        }
        if($status !='' && $status != 4)
        {
            $query->where('is_validate','=',$status);
        }
        else 
        {
            $query->whereIn('is_validate',[1,2]);
        }
//         $defaultCatid = Category::where(array('app'=>'teaches','pid'=>0))->first()->cat_id;
//         if($catid <= 0 || empty($catid))
//         {
//             $catid = $defaultCatid;
//         }
//         $allCateIds = Category::getCategoryIds($catid);
        $teaches = $query->orderBy("updated_at","desc")->paginate(20);
    
        return view('admin.teaches.index')->with('teaches',$teaches)->with('catid',$catid)
                ->with('categorys',$this->catgory)->with('nowtype',$catid)->with('usernmae',$username)
                ->with('status',$status)->with('username',$username)->with('title',$title);
    }
    
    /**
     * 充电加油待审核列表
     */
    public function noverify(Request $req)
    {
        if(!$this->user->can('viewTeaches')) abort(405);
        
        $catid = $req->input('cateid',0);
//         $defaultCatid = Category::where(array('app'=>'teaches','pid'=>0))->first()->cat_id;
//         if($catid <= 0 || empty($catid))
//         {
//             $catid = $defaultCatid;
//         }
//         $allCateIds = Category::getCategoryIds($catid);
        $teaches = Teaches::where('is_validate',0)->orderBy("updated_at","desc")->paginate(20);
        
        return view('admin.teaches.noverify')->with('teaches',$teaches)->with('catid',$catid)->with('categorys',$this->catgory);
    }
    
    /**
     * 用于审核  
     * 文章详情展示
     */
    public function show($id)
    {
        if(!$this->user->can('editTeaches')) return $this->formatJson('error',$this->permerror);
        
        $newsTag = array();
        
        $result = Teaches::find($id);
        if(empty($result))
        {
            return $this->formatJson('false');
        }
        
        if(count($result->categorys) <= 0)
        {
            return $this->formatJson('false');
        }
        
        foreach ($result->tags as $tag)
        {
            $newsTag[] = Tags::where('tags_id','=',$tag->tags_id)->first()->tags_name;
        }
        $result->username = $result->user->name;
        $result->nowcate = $result->categorys->cat_name;
        $result->parentcate = count($result->categorys->parentCate)>0 ? $result->categorys->parentCate->cat_name.">":"";
        $result->topcate = count($result->categorys->parentCate)>0?(count($result->categorys->parentCate->parentCate)>0 ? $result->categorys->parentCate->parentCate->cat_name.">":""):"";
        $result->newsTag = $newsTag;
        $result->thumburl = count($result->attachment)>0?$result->attachment->url:'';
        
        return $this->formatJson('success','获取数据成功！',$result);
    }
    
    /**
     * 新增  经验文章
     */
    public function create(Request $req)
    {
        
        if(!$this->user->can('editTeaches')) abort(405);
        
        return  view('admin.teaches.create')->with('type',$this->catgory)->with('companys',$this->companys);
    }
    
    /**
     * 充电加油 编辑
     * @param int $id 文章编号
     */
    public function edit($id)
    {
        if(!$this->user->can('editTeaches')) abort(405);
        
        $categorys=array();
        
        $result = Teaches::find($id);
        if(empty($result))
        {
            abort(404);
        }
        
        if(count($result->categorys) <= 0)
        {
            abort(403);
        }
        $categorys = $this->getCate($result->cat_id, $result->categorys->pid,"teaches");
        $newsTag = array();
        foreach ($result->tags as $tag)
        {
            $newsTag[] = Tags::where('tags_id','=',$tag->tags_id)->first()->tags_name;
        }
        $result->username = $result->user->name;
        $result->nowcate = $result->categorys->cat_name;
        $result->parentcate = count($result->categorys->parentCate)>0 ? $result->categorys->parentCate->cat_name.">":"";
        $result->topcate = count($result->categorys->parentCate)>0?(count($result->categorys->parentCate->parentCate)>0 ? $result->categorys->parentCate->parentCate->cat_name.">":""):"";
        
        return  view('admin.teaches.create')
            ->with('type',$this->catgory)
            ->with('result',$result)
            ->with('categorys',$categorys)
            ->with('newstag',implode(",", $newsTag))
            ->with('companys',$this->companys)
            ->with('item',$this->item);
    }
    
     /**
      * 充电加油课程数据保存
      * @param Request $req
      */
     public function store(Request $req)
     {
         if(!$this->user->can('editTeaches')) 
             return $this->formatJson('error',$this->permerror);
         
         $data = $req->only('teachesid','name','type','child_1','child_2','child_3','description','thumb','notice','level',
                'meta_value','price','sort','author_id','education','is_recommond','tagsinput','user_id');
         $tagids = array();
         $tags = strToArray($data['tagsinput'], ",");
         foreach ($tags as $tg){
             if(!empty(trim($tg)))
             {
                 $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                 $tagids[] = $tagsModel->tags_id;
             }
         }
         $categoryId = $this->getTypes($data['type'], $data['child_1'], $data['child_2'], $data['child_3']);
         if(empty($categoryId))
         {
             return Response::json(array('status'=>'falied','msg'=>'分类不可为空，请选择分类！'));
         }
         if($data['teachesid'] && is_numeric($data['teachesid']) && $data['teachesid'] > 0)
         {
             $teaches               = Teaches::find($data['teachesid']);
             $teaches->name         = $data['name'];
             $teaches->cat_id       = $categoryId;
             $teaches->description  = $data['description'];
             $teaches->notice       = $data['notice'];
             $teaches->thumb        = $data['thumb'];
             $teaches->level        = $data['level'];
             $teaches->meta_value   = $data['meta_value'];
             $teaches->price        = $data['price'];
             $teaches->author_id    = $data['author_id'];
             $teaches->sort         = $data['sort'];
             $teaches->is_validate  = $teaches['is_validate'];
             if( $teaches->is_validate >= 1){
                 $teaches->validated_at = date('Y-m-d H:i:s');
             }
             $teaches->is_recommond = $data['is_recommond'];
             $teaches->education = $data['education'];
             $teaches->save();
         }
         else
         {
             $item = array(
                 'name'         => $data['name'],
                 'cat_id'       => $categoryId,
                 'description'  => $data['description'],
                 'notice'       => trim($data['notice']),
                 'thumb'        => $data['thumb'],
                 'level'        => $data['level'],
                 'meta_value'   => $data['meta_value'],
                 'price'        => $data['price'],
                 'user_id'      => $this->user->id,
                 'author_id'    => $data['author_id'],
                 'sort'         => $data['sort'],
                 'is_validate'  => 1,
                 'validated_at' => date('Y-m-d H:i:s'),
                 'is_recommond' => $data['is_recommond'],
                 'education'    => trim($data['education'])
             );
             $teaches = Teaches::firstOrCreate($item);
         }
         //建立关联 文章与标签
         TeachesTags::where('teaches_id','=',$teaches->id)->delete();
         foreach ($tagids as $tgd){
             TeachesTags::firstOrCreate(['tags_id'=>$tgd,'teaches_id'=>$teaches->id]);
         }
         return Response::json(array('status'=>'success','msg'=>'保存数据成功！','id'=>$teaches->id,'redirectUrl'=>'/admin/teaches/index'));
     }
    
    /**
     * 文章审核
     * @param Request $req
     */
    public function teachesValidate(Request $req)
    {
        if(!$this->user->can('editTeaches'))
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('is_validate','id');
        if(empty($data['is_validate']))
        {
            return $this->formatJson('error','请选择审核结果！');
        }
        $teaches = Teaches::find($data['id']);
        $teaches->is_validate = $data['is_validate'];
        $teaches->validated();
        if($teaches->is_validate == 1)
            return $this->formatJson('success',"文章：［ ".$teaches->name." ］审核通过！",$teaches,'/admin/teaches/noverify');
        else if($teaches->is_validate == 2)
            return $this->formatJson('success',"文章：［ ".$teaches->name." ］不通过！",$teaches,'/admin/teaches/noverify');
            
    }
    
    /**
     * 删除
     */
    public function destroy($news_id)
    {
        if(!$this->user->can('deleteTeaches'))
            return $this->formatJson('error',$this->permerror);
        
        $news = Teaches::find($news_id);
        $news->delete();
        return  Response::json(array('status'=>'success','msg'=>'文章：［'.$news->name.'］ 删除成功'));
    }
    
    
    /**
     * 首页推荐 0 不推荐  1 推荐
     */
    public function recommond(Request $request)
    {
        if(!$this->user->can('editTeaches'))
            return $this->formatJson('error',$this->permerror);
        
        $id = $request->input('id');
        $is_recommond = $request->input('is_disabled');
        $teaches = Teaches::find($id);
        
        $teaches->is_recommond = $is_recommond = $is_recommond > 0 ? 0 : 1;
        if ($teaches->save())
            return  Response::json(array('status'=>'success','msg'=>'广告位', 'data' => $is_recommond));
    }
    
    /**
     * 首页热门课程推荐 0 不推荐  1 推荐
     */
    public function toHots(Request $request)
    {
        if(!$this->user->can('editTeaches'))
            return $this->formatJson('error',$this->permerror);
    
        $id = $request->input('id');
        $is_recommond = $request->input('is_disabled');
        $teaches = Teaches::find($id);
    
        $teaches->is_hot = $is_recommond = $is_recommond > 0 ? 0 : 1;
        if ($teaches->save())
            return  Response::json(array('status'=>'success','msg'=>'推荐成功！', 'data' => $is_recommond));
    }
    
    /**
     * 课程列表
     * @param integer $id
     */
    public function chapterList($id)
    {
        if(!$this->user->can('viewTeaches')) abort(405);
        
        $result = Teaches::find($id);
        
        return view('admin.teaches.chapter')->with('result',$result);
    }
    
    /**
     * 章节保存
     * @param Request $req
     */
    public function chapterAdd(Request $req) 
    {
        if(!$this->user->can('editTeaches'))
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('name','user_id','price','teachesid','chapterid');
        if($data['chapterid'] && is_numeric($data['chapterid']) && $data['chapterid'] > 0)
        {
            $chapter = TeachesChapter::find($data['chapterid']);
            $chapter->name = $data['name'];
            $chapter->price = $data['price'];
            $chapter->save();
        }
        else
        {
            $item = array(
              'teaches_id'      => $data['teachesid'],
              'name'            => $data['name'],
              'price'           => $data['price'],
              'user_id'         => $this->user->id
            );
            $chapter = TeachesChapter::firstOrCreate($item);
        }
        $teachesid = $chapter->teaches_id;
        if(!empty($chapter) && $chapter->id > 0)
             return  Response::json(array('status'=>'success','msg'=>'保存数据成功！', 'id'=>$chapter->id,'redirectUrl'=>url('/admin/teaches/index/chapter/'.$teachesid)));
        else 
            return  Response::json(array('status'=>'success','msg'=>'保存数据失败！'));
    }
    
    /**
     * 充电加油 章节列表删除
     */
    public function chapterDel($id)
    {
        if(!$this->user->can('deleteTeaches'))
            return $this->formatJson('error',$this->permerror);
        
        $chapter = TeachesChapter::find($id);
        if(empty($chapter))
        {
            return $this->formatJson('error','抱歉，您找的资源不存在');
        }
        
        if($chapter->delete()){
            TeachesContent::where('chapter_id','=',$id)->delete();
            return $this->formatJson('success','章节：［'.$chapter->name.']删除成功！');
        }
    }
}
